/**
 * 
 */
package com.kylin.erp.oa.system.service;

import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Service;

import com.kylin.erp.dbmodel.TDepts;

/**
 * 系统组织结构服务类
 * 
 * @author huxiang
 * 
 */
@Service
public class SystemOrgnService {

	/**
	 * 获取某个公司下面的某个部门树
	 * @param companyId
	 * @param orgnId
	 * @return
	 */
	public JSONArray getUserOrgns(String companyId, int orgnId) {

		JSONArray ztreeNodes = new JSONArray();

		List<TDepts> topDepts = TDepts.dao
				.find("select * from t_depts where company_id_ = ? and parent_id_ = ?",
						companyId, orgnId);
		for (int i = 0; i < topDepts.size(); i++) {

			TDepts dept = topDepts.get(i);
			ztreeNodes.add(this.buildZtreeNode(dept));
		}

		return ztreeNodes;
	}

	private Object buildZtreeNode(TDepts dept) {

		JSONObject ob = new JSONObject();
		ob.put("name", dept.getStr("name_"));
		ob.put("id", dept.getInt("id_"));
		List<TDepts> subdepts = TDepts.dao.find(
				"select * from t_depts where parent_id_ = ?",
				dept.getInt("id_"));
		JSONArray ja = new JSONArray();
		if (null != subdepts && subdepts.size() > 0) {
			for (int i = 0; i < subdepts.size(); i++) {
				TDepts tdept = subdepts.get(i);
				ja.add(this.buildZtreeNode(tdept));
			}
			ob.put("children", ja);
		} else {

		}
		return ob;
	}
}
